package com.dawnClass.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.dawnClass.pojo.Consumer;
import com.dawnClass.VO.OrderOrderDetailVO;
import com.dawnClass.service.OrderService;
import com.dawnClass.config.AlipayConfig;
import com.dawnClass.service.PayService;
import com.dawnClass.util.ServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class AliPayController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    @GetMapping("pay")
    @ResponseBody
    public ModelAndView payOrderdetail(HttpSession session){
        ServiceResponse consumerResponse = (ServiceResponse)session.getAttribute("ServiceResponse");
        Consumer consumer = (Consumer) consumerResponse.getdata();
        ServiceResponse orderOrderDetailVO =  orderService.getByOrdId(consumer.getConsumerId());
        ModelAndView mav = new ModelAndView();
        mav.addObject("payDetail",orderOrderDetailVO);
        mav.setViewName("pay/toPay");
        return mav;
    }

    // 1. 支付：调用支付宝支付
    @PostMapping("pay")
    @ResponseBody
    public String pay(Integer orderId){

        OrderOrderDetailVO orderOrderDetailVO =  orderService.getById(orderId);

        //(1)初始化AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                                                            AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                                                            AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //(2)设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url); // 同步请求支付
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url); // 异步请求支付


        //(3)支付请求中的订单信息 --- alirequest  context

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //String out_trade_no = "124341141312";

        //付款金额，必填
        //String total_amount = "0.81";

        //订单名称，必填
        //String subject = "爆炒李纪元";

        //商品描述，可空
        //String body = "采用新鲜李纪元经过多到工序精心烹制";


        String out_trade_no = orderOrderDetailVO.getOrder().getOrderNum();

        String subject = orderOrderDetailVO.getCourse().getCourseName();
        String timeout_express = "1c";// 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。

        Float total_amount = orderOrderDetailVO.getOrder().getOrderTotal();
        String body = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String payResult = null;
        try {
            AlipayResponse alipayResponse =  alipayClient.pageExecute(alipayRequest);

            System.out.println("pay code:"+ alipayResponse.getCode());
            System.out.println("pay getSubCode:"+ alipayResponse.getSubCode());
            System.out.println("pay getMsg:"+ alipayResponse.getMsg());
            System.out.println("pay isSuccess:"+ alipayResponse.isSuccess());

            payResult =  alipayResponse.getBody();// getBody() 支付后，支付宝返回的支付的信息
            System.out.println("支付宝返回的支付的信息：" + payResult);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return  payResult;
    };

    // 支付后的 获得 支付宝的信息 payResult --->request
    @GetMapping("/alipayReturnNotice")
    public ModelAndView returnNotice(HttpServletRequest request,HttpServletResponse response , String out_trade_no){

        System.out.println(out_trade_no);
        System.out.println("同步返回页面操作。。。。。");

        ModelAndView mav = new ModelAndView("pay/paySuccess");
        mav.setViewName("pay/paySuccess");
        Map<String,String[]> map= request.getParameterMap();
        
        System.out.println(">>>>>支付后的 获得 支付宝的信息 " + map);
        System.out.println(map.values());

        //修改订单状态，创建订单
        int courseId = payService.updateOrderflow(out_trade_no);

        //查询新的流水
        ServiceResponse serviceResponse = payService.getByOrdNum(out_trade_no);
        mav.addObject("flowDetail",serviceResponse);
        mav.addObject("courseId",courseId);
        return mav;
    }

    @GetMapping("/alipayNotifyNotice")
    @ResponseBody
    public String notifyNotice(HttpServletRequest request,HttpServletResponse response , String out_trade_no){
        System.out.println("异步返回页面操作。。。。。");
        Map<String,String[]> map= request.getParameterMap();
        System.out.println("支付后的 获得 支付宝的信息 " + map);
        payService.updateOrderflow(out_trade_no);

        //order_num
        //course_name
        //flow_cost
        //flow_pay_time
        //页面显示几秒通过courseId进入详情页
        return "pay/paySuccess";
    }
}



